import json

from django.db import IntegrityError
from django.shortcuts import render, HttpResponse, redirect

from utils.pager import PageInfo
from worksite import models
from worksite.myfunc import login_wrapper


# Create your views here.

#  查看所有的主机账户和密码
@login_wrapper
def userinfo(request):
    all_count = models.User.objects.all().count()
    page_info = PageInfo(request.GET.get('page'), all_count, 30, '/userinfo.html', 11)
    ret = models.User.objects.all().order_by("-id")[page_info.start():page_info.end()]

    # 序号自增
    current_page = request.GET.get('page')
    # print(current_page)
    if current_page is None:
        #     # print(current_page)
        #     # print(start)
        current_page = 1
        start = (current_page - 1) * 30
    else:
        current_page = int(request.GET.get('page'))
        start = (current_page - 1) * 30

    # return render(request, "userinfo.html", {"userinfo": hasven,"vendor": host_info,})
    return render(request, "userinfo.html", {"userinfo": ret, 'page_info': page_info, "start": start})
    # return HttpResponse("ok")


#  首页
def index(request):
    # 软件加固
    swmonth1 = models.MyworkSoftware.objects.filter(date__startswith="2018-01").count()
    swmonth2 = models.MyworkSoftware.objects.filter(date__startswith="2018-02").count()
    swmonth3 = models.MyworkSoftware.objects.filter(date__startswith="2018-03").count()
    swmonth4 = models.MyworkSoftware.objects.filter(date__startswith="2018-04").count()
    swmonth5 = models.MyworkSoftware.objects.filter(date__startswith="2018-05").count()
    swmonth6 = models.MyworkSoftware.objects.filter(date__startswith="2018-06").count()
    swmonth7 = models.MyworkSoftware.objects.filter(date__startswith="2018-07").count()
    swmonth8 = models.MyworkSoftware.objects.filter(date__startswith="2018-08").count()
    swmonth9 = models.MyworkSoftware.objects.filter(date__startswith="2018-09").count()
    swmonth10 = models.MyworkSoftware.objects.filter(date__startswith="2018-10").count()
    swmonth11 = models.MyworkSoftware.objects.filter(date__startswith="2018-11").count()
    swmonth12 = models.MyworkSoftware.objects.filter(date__startswith="2018-12").count()

    # 基线加固
    bsmonth1 = models.MyworkBaseline.objects.filter(date__startswith="2018-01").count()
    bsmonth2 = models.MyworkBaseline.objects.filter(date__startswith="2018-02").count()
    bsmonth3 = models.MyworkBaseline.objects.filter(date__startswith="2018-03").count()
    bsmonth4 = models.MyworkBaseline.objects.filter(date__startswith="2018-04").count()
    bsmonth5 = models.MyworkBaseline.objects.filter(date__startswith="2018-05").count()
    bsmonth6 = models.MyworkBaseline.objects.filter(date__startswith="2018-06").count()
    bsmonth7 = models.MyworkBaseline.objects.filter(date__startswith="2018-07").count()
    bsmonth8 = models.MyworkBaseline.objects.filter(date__startswith="2018-08").count()
    bsmonth9 = models.MyworkBaseline.objects.filter(date__startswith="2018-09").count()
    bsmonth10 = models.MyworkBaseline.objects.filter(date__startswith="2018-10").count()
    bsmonth11 = models.MyworkBaseline.objects.filter(date__startswith="2018-11").count()
    bsmonth12 = models.MyworkBaseline.objects.filter(date__startswith="2018-12").count()

    # 软件版本加固信息统计
    openssh_num = models.MyworkSoftwareAndSoftware.objects.filter(software_id__lte=3).count()
    openssl_num = models.MyworkSoftwareAndSoftware.objects.filter(software_id__gte=4, software_id__lte=7).count()
    ntp_num = models.MyworkSoftwareAndSoftware.objects.filter(software_id__gte=8, software_id__lte=10).count()
    ntpdate_num = models.MyworkSoftwareAndSoftware.objects.filter(software_id=11).count()
    wget_num = models.MyworkSoftwareAndSoftware.objects.filter(software_id=12).count()
    vsftpd_num = models.MyworkSoftwareAndSoftware.objects.filter(software_id__gte=13, software_id__lte=14).count()
    # print(len(openssh))

    return render(request, "index.html",
                  {'swmonth1': swmonth1, 'swmonth2': swmonth2, 'swmonth3': swmonth3, 'swmonth4': swmonth4,
                   'swmonth5': swmonth5,
                   'swmonth6': swmonth6, 'swmonth7': swmonth7, 'swmonth8': swmonth8, 'swmonth9': swmonth9,
                   'swmonth10': swmonth10,
                   'swmonth11': swmonth11, 'swmonth12': swmonth12, 'bsmonth1': bsmonth1, 'bsmonth2': bsmonth2,
                   'bsmonth3': bsmonth3, 'bsmonth4': bsmonth4, 'bsmonth5': bsmonth5,
                   'bsmonth6': bsmonth6, 'bsmonth7': bsmonth7, 'bsmonth8': bsmonth8, 'bsmonth9': bsmonth9,
                   'bsmonth10': bsmonth10,
                   'bsmonth11': bsmonth11, 'bsmonth12': bsmonth12, 'openssh_num': openssh_num,
                   'openssl_num': openssl_num, 'ntp_num': ntp_num, 'ntpdate_num': ntpdate_num, 'wget_num': wget_num,
                   'vsftpd_num': vsftpd_num, })

    #  删除主机用户和密码

@login_wrapper
def userinfo_del(request):
    # print(request.GET)
    del_id = request.GET.get("id", None)
    # print(del_id)
    if del_id is None:
        del_id = request.POST.get("id", None)
        # print(del_id)
        if del_id:
            obj = models.User.objects.get(id=del_id)
            obj.delete()
            return HttpResponse("ok")
    #     print(del_id)

    # 判断数据是否存在
    elif del_id:
        obj = models.User.objects.get(id=del_id)
        # return redirect("/userinfo/")
        obj.delete()

        return redirect("/userinfo.html")
    else:
        return HttpResponse("没有所选的数据")


# 查看所有完成的基线加固
@login_wrapper
def baseline(request):
    all_count = models.MyworkBaseline.objects.all().count()
    page_info = PageInfo(request.GET.get('page'), all_count, 30, '/baseline.html', 11)
    ret = models.MyworkBaseline.objects.all().order_by("-id")[page_info.start():page_info.end()]

    # 序号自增
    current_page = request.GET.get('page')
    # print(current_page)
    if current_page is None:
        #     # print(current_page)
        #     # print(start)
        current_page = 1
        start = (current_page - 1) * 30
    else:
        current_page = int(request.GET.get('page'))
        start = (current_page - 1) * 30

    return render(request, "baseline.html", {"baseline": ret, 'page_info': page_info, "start": start})


# 查看所有的软件加固
@login_wrapper
def myworksoftware(request):
    all_count = models.MyworkSoftwareAndSoftware.objects.all().count()

    page_info = PageInfo(request.GET.get('page'), all_count, 30, '/myworksoftware.html', 11)
    soft = models.MyworkSoftwareAndSoftware.objects.all().order_by("-id")[page_info.start():page_info.end()]
    # print(page_info.all_pager)

    # 序号自增
    current_page = request.GET.get('page')
    # print(current_page)
    if current_page is None:
        #     # print(current_page)
        #     # print(start)
        current_page = 1
        start = (current_page - 1) * 30
    else:
        current_page = int(request.GET.get('page'))
        start = (current_page - 1) * 30

    # print(ret[0].mywork_software.ip,ret[0].mywork_software.date)

    # return render(request, "myworksoftware.html", {"software": soft, 'page_info': page_info,})
    return render(request, "myworksoftware.html", {"software": soft, 'page_info': page_info, "start": start})
    # return HttpResponse("ok")


# 修改软件加固信息
@login_wrapper
def edit_myworksoftware(request):
    if request.method == "GET":
        edit_id = request.GET.get("id", None)
        obj = models.MyworkSoftwareAndSoftware.objects.get(id=edit_id)
        # sw_obj=obj.software
        # print(obj.software_id)

        mysw = obj.mywork_software
        # print(mysw)
        allsw = models.Software.objects.all()
        allos = models.Os.objects.all()
        # ip=obj.mywork_software.ip
        # print(ip)
        return render(request, "edit_data/edit_myworksoftware.html",
                      {"mysw": mysw, "os": allos, "sws": allsw, "obj": obj, "myworkandsoftware_id": edit_id})
    # print(request.POST.get)
    ip = request.POST.get("ip")
    # print(ip)
    date = request.POST.get("date")
    os_id = request.POST.get("os")
    software_id = request.POST.get("software_id")
    myworkandsoftware_id = request.GET.get("myworkandsoftware_id")
    # print(myworkandsoftware_id)
    myworksoftware_id = models.MyworkSoftwareAndSoftware.objects.get(id=myworkandsoftware_id).mywork_software_id
    myworksoftware_obj = models.MyworkSoftware.objects.get(id=myworksoftware_id)

    # print(myworksoftware_obj)
    # print(myworksoftware_obj.os_id)

    myworksoftware_obj.os_id = os_id
    myworksoftware_obj.date = date
    myworksoftware_obj.ip = ip
    myworksoftware_obj.save()

    myworkandsoftware_obj = models.MyworkSoftwareAndSoftware.objects.get(id=myworkandsoftware_id)
    myworkandsoftware_obj.software_id = software_id
    myworkandsoftware_obj.save()

    # return HttpResponse("ok")
    return redirect("/myworksoftware.html")



# 修改账户信息
@login_wrapper
def edit_userinfo(request):
    if request.method == "POST":
        user = request.POST.get("user")
        password = request.POST.get("password")
        rootpwd = request.POST.get("rootpwd")
        management = request.POST.get("management")
        edit_id = request.GET.get("user_id")

        # print(user,password,rootpwd,management,edit_id)

        def foo():
            user_obj = models.User.objects.get(id=edit_id)
            user_obj.user = user

            # print(host_obj.ip)
            # host_obj.save()
            user_obj.password = password
            user_obj.root_password = rootpwd
            user_obj.management = management
            user_obj.save()

        if edit_id is None:
            edit_id = request.POST.get("user_id")
            foo()
            return HttpResponse("OK")
        # print(request.POST.get)
        # print(edit_id,ip,user,password,rootpwd,management)

        foo()
        return redirect("/userinfo.html")

    edit_id = request.GET.get("id")
    # print(request.GET.get("id"))
    user_obj = models.User.objects.get(id=edit_id)
    return render(request, "edit_data/edit_userinfo.html", {"user_obj": user_obj})


# 安全基线加固修改
@login_wrapper
def edit_baseline(request):

    if request.method == "POST":
        up_id = request.GET.get("myworkbaseline_id")
        ip = request.POST.get("ip")
        date = request.POST.get("date")
        os_id = request.POST.get("os")
        # print(request.POST)
        baseline_obj = models.MyworkBaseline.objects.get(id=up_id)
        baseline_obj.ip = ip
        baseline_obj.date = date
        baseline_obj.os_id = os_id
        baseline_obj.save()
        # return HttpResponse("OK")
        return redirect("/baseline.html")

    edit_id = request.GET.get("id")
    print(edit_id)
    myworkbaseline_obj = models.MyworkBaseline.objects.get(id=edit_id)
    allos = models.Os.objects.all()

    return render(request, "edit_data/edit_baseline.html", {"baseline_obj": myworkbaseline_obj, "os": allos})


# 所有主机信息
@login_wrapper
def hostinfo(request):
    all_count = models.Host.objects.all().count()

    page_info = PageInfo(request.GET.get('page'), all_count, 30, '/hostinfo.html', 11)
    vendors = models.Host.objects.all().order_by("-id")[page_info.start():page_info.end()]

    # 序号自增
    current_page = request.GET.get('page')
    # print(current_page)
    if current_page is None:

        current_page = 1
        start = (current_page - 1) * 30
    else:
        current_page = int(request.GET.get('page'))
        start = (current_page - 1) * 30

    return render(request, "hostinfo.html", {"vendors": vendors, 'page_info': page_info, "start": start})



# 所有软件信息
@login_wrapper
def softwareinfo(request):
    softwares = models.Software.objects.all().order_by("id")

    return render(request, "softwareinfo.html", {"softwares": softwares})


# 模态框添加用户
@login_wrapper
def modal_add_userinfo(request):
    ret = {"status": "True", "message": None}

    if request.method == "POST":
        ip = request.POST.get("ip")
        host_id = models.Host.objects.filter(ip=ip).first().id
        print(host_id)
        user = request.POST.get("user")
        password = request.POST.get("password")
        rootpwd = request.POST.get("rootpwd")
        management = request.POST.get("management")
        print(ip, user, password, rootpwd, management)
        try:
            models.User.objects.create(host_id=host_id, user=user, password=password, management=management,
                                       root_password=rootpwd)
            # print(ip, user, password, rootpwd, management,operating)
        except IntegrityError as e:
            ret['status'] = False
            ret['message'] = "IP不存在!请确认IP是否输入正确！！"
        return HttpResponse(json.dumps(ret))
    return render(request, "add_data/add_userinfo.html")


# 主机用户密码信息添加IP存在检测
@login_wrapper
def ip_check(request):
    ret = {"status": "True", "message": None}
    # message = None
    ip = request.POST.get("ip")
    # print(ip)
    try:
        ret_ip = models.Host.objects.get(ip=ip)
    except Exception as e:
        ret["message"] = "IP错误或不存在，请先添加Host列表"
        ret["status"] = False
    return HttpResponse(json.dumps(ret))
    # print(ret_ip)

    # return render(request, "add_userinfo.html", {"message": message})


# 数据
@login_wrapper
def data(request):
    baseline_num = models.MyworkBaseline.objects.all().count()
    software_num = models.MyworkSoftwareAndSoftware.objects.all().count()

    # ret = {"baseline_num": baseline_num, "software_num": software_num}
    ret = {"name": ["软件", "基线"], "data": [software_num, baseline_num]}

    return HttpResponse(json.dumps(ret))


# 删除软件加固
@login_wrapper
def delmyworksoftware(request):
    edit_id = request.GET.get("id", None)
    models.MyworkSoftwareAndSoftware.objects.get(id=edit_id).delete()
    # print(obj.software.software)

    return redirect("/myworksoftware.html")


# 删除基线加固
@login_wrapper
def del_myworkbaseline(request):
    edit_id = request.GET.get("id")
    models.MyworkBaseline.objects.get(id=edit_id).delete()
    return redirect("/baseline.html")


# 修改主机信息
@login_wrapper
def edit_hostinfo(request):

    if request.method == "POST":
        ip = request.POST.get("ip")
        vendor_id = request.POST.get("vendor")
        service_id = request.POST.get("service")
        network_id = request.POST.get("network")
        edit_id = request.GET.get("id")
        host_obj = models.Host.objects.get(id=edit_id)
        # print(edit_id,ip,vendor,service,network,)

        host_obj.service_id = service_id
        host_obj.ip = ip
        host_obj.vendor_id = vendor_id
        host_obj.network_id = network_id
        host_obj.save()
        return redirect("/hostinfo.html")

    edit_id = request.GET.get("id")
    services = models.Service.objects.all()
    host_obj = models.Host.objects.get(id=edit_id)
    networks = models.Network.objects.all()
    os = models.Os.objects.all()
    vendors = models.Vendor.objects.all()
    return render(request, "edit_data/edit_hostinfo.html",
                  {"host_obj": host_obj, "networks": networks, "os": os, "services": services, "vendors": vendors})


# 删除主机信息
@login_wrapper
def del_hostinfo(request):
    del_id=request.GET.get("id")
    print(del_id)
    models.Host.objects.get(id=del_id).delete()
    return redirect("/hostinfo.html")
